﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace JLL.China.Infrastructure.Repositories.Listings
{
    using System.Data.Linq;
    using JLL.China.Model;
    using JLL.China.Model.DTO;
   
    public class ListingsRepository : SQLRepositoryBase<Model.Listings, int>, IListingsRepository
    {
        public override Listings FindBy(int key)
        {
            var listing = DataContext.Listings.SingleOrDefault(x => key.Equals(x.Listing_ID));

            if (listing != null)
            {
                return ListingFactory.FromLINQObject(listing);
            }
            else
            {
                return null;
            }
   
        }

        public override IList<Listings> FindAll()
        {
            throw new NotImplementedException();
        }

        protected override void PersistNewItem(Listings item)
        {
            DataContext.Listings.InsertOnSubmit(ListingFactory.ToLINQObject(item));
        
        }
        protected override void PersistUpdatedItem(Listings item)
        {
          
            var listing = DataContext.Listings.SingleOrDefault(x =>x.Listing_ID.Equals(item.ID));

            if (listing != null)
            {
                listing.Longitude = item.Longitude;
                listing.Latitude = item.Latitude;
            }
            else
            {
                throw new Exception("Can't update!");
            }
           
        }
        protected override void PersistDeletedItem(Listings item)
        {
            throw new NotImplementedException();
        }

        public Model.Listings FindById(int id)
        {
            var listing = DataContext.ListingItems.SingleOrDefault(x =>x.Listing_ID.Equals(id));

            if (listing != null)
            {
                return new Listings
                {
                    ID = Int32.Parse(listing.Listing_ID.ToString()),
                    PropertyFor = listing.PropertyFor,
                    ProjectNameFID = listing.ProjectNameFID,
                    PropertyClsssm = listing.PropertyClsssm,
                    StreetNameFID = listing.StreetNameFID,
                    PropertyTypeFID = listing.PropertyTypeFID,
                    CountryFID = listing.CountryFID,
                    CityFID = listing.CityFID,
                    LocaltionFID = listing.LocaltionFID,
                    SubAreaFID = listing.SubAreaFID,
                    Tenure = listing.Tenure,
                    FloorLevel = listing.FloorLevel,
                    TotalFloor = listing.TotalFloor,
                    FloorArea_SM = listing.FloorArea_SM,
                    FloorArea_SF = listing.FloorArea_SF,
                    FloorArea_SY = listing.FloorArea_SY,
                    FloorAreaUnit = listing.FloorAreaUnit,
                    LandArea_SF = listing.LandArea_SF,
                    LandArea_SM = listing.LandArea_SM,
                    LandArea_SY = listing.LandArea_SY,
                    AskingPriceLocal = listing.AskingPriceLocal,
                    AskingPriceUSD = listing.AskingPriceUSD,
                    PriceInRMBPerSQMLocal = listing.PriceInRMBPerSQMLocal,
                    PriceInRMBPerSQMUSD = listing.PriceInRMBPerSQMUSD,
                    ListingType = listing.ListingType,
                    ListingCat = listing.ListingCat,
                    StatusFID = listing.StatusFID,
                    NewLaunch = listing.NewLaunch,
                    Longitude = listing.Longitude,
                    Latitude = listing.Latitude,
                    Bedroom = listing.Bedroom,
                    Bathroom = listing.Bathroom,
                    MemberFID = listing.MemberFID,
                    CreateDate = listing.CreateDate,
                    ListingDate = listing.ListingDate,
                    ListingExpiry = listing.ListingExpiry,
                    PriceUnit = listing.PriceUnit,
                    EfficiencyRate = listing.EfficiencyRate,
                    Auction = listing.Auction,
                    Description = listing.Description,
                    DescriptionLocal = listing.DescriptionLocal,
                    Features = listing.Features,
                    Facilities = listing.Facilities,
                    HouseNumber = listing.HouseNumber,
                    ProjectName = listing.ProjectName,
                    City = listing.City,
                    Location = listing.Location,
                    SubArea = listing.Subarea,
                    HotImage_FID = listing.HotImage_FID,
                    HotImage_Path = listing.HotImage_Path,
                    PropertyTypeName = listing.PropertyType
                    
                };
                
            }
            else
            {
                return null;
            }
            
           

        }

        public IList<Model.Listings> Search(ListingSearchCriteria searchCriteria)
        {

            var items = SearchByCriteria(searchCriteria).OrderBy(x=>x.Listing_ID);
            var result = new List<Model.Listings>();
            var list = items.ToList();
            
            foreach (var listing in list)
            {
                result.Add(new Model.Listings { 
                     
                    ID = Int32.Parse(listing.Listing_ID.ToString()),
                    PropertyFor = listing.PropertyFor,
                    ProjectNameFID = listing.ProjectNameFID,
                    PropertyClsssm = listing.PropertyClsssm,
                    StreetNameFID = listing.StreetNameFID,
                    PropertyTypeFID = listing.PropertyTypeFID,
                    CountryFID = listing.CountryFID,
                    CityFID = listing.CityFID,
                    LocaltionFID = listing.LocaltionFID,
                    SubAreaFID = listing.SubAreaFID,
                    Tenure = listing.Tenure,
                    FloorLevel = listing.FloorLevel,
                    TotalFloor = listing.TotalFloor,
                    FloorArea_SM = listing.FloorArea_SM,
                    FloorArea_SF = listing.FloorArea_SF,
                    FloorArea_SY = listing.FloorArea_SY,
                    FloorAreaUnit = listing.FloorAreaUnit,
                    LandArea_SF = listing.LandArea_SF,
                    LandArea_SM = listing.LandArea_SM,
                    LandArea_SY = listing.LandArea_SY,
                    AskingPriceLocal = listing.AskingPriceLocal,
                    AskingPriceUSD = listing.AskingPriceUSD,
                    PriceInRMBPerSQMLocal = listing.PriceInRMBPerSQMLocal,
                    PriceInRMBPerSQMUSD = listing.PriceInRMBPerSQMUSD,
                    ListingType = listing.ListingType,
                    ListingCat = listing.ListingCat,
                    StatusFID = listing.StatusFID,
                    NewLaunch = listing.NewLaunch,
                    Longitude = listing.Longitude,
                    Latitude = listing.Latitude,
                    Bedroom = listing.Bedroom,
                    Bathroom = listing.Bathroom,
                    MemberFID = listing.MemberFID,
                    CreateDate = listing.CreateDate,
                    ListingDate = listing.ListingDate,
                    ListingExpiry = listing.ListingExpiry,
                    PriceUnit = listing.PriceUnit,
                    EfficiencyRate = listing.EfficiencyRate,
                    Auction = listing.Auction,
                    Description = listing.Description,
                    DescriptionLocal = listing.DescriptionLocal,
                    Features = listing.Features,
                    Facilities = listing.Facilities,
                    HouseNumber = listing.HouseNumber,
                    ProjectName = listing.ProjectName,
                    City = listing.City,
                    Location = listing.Location,
                    SubArea = listing.Subarea,
                    HotImage_FID = listing.HotImage_FID,
                    HotImage_Path = listing.HotImage_Path,
                    PropertyTypeName = listing.PropertyType
                    
                });
            }

            return result;
        }
        private IQueryable<LINQ2SQL.ListingItem> SearchByCriteria(ListingSearchCriteria searchCriteria)
        {
            var items = (from m in DataContext.ListingItems
                         select m);

            if (searchCriteria.CountryID.HasValue)
            {
                //Local or International
                items = items.Where(x => x.CountryFID == searchCriteria.CountryID.Value);
            }
            else
            {
                int countryID =  Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["CountryID"].ToString());
                items = items.Where(x => x.CountryFID != countryID );
       
            }

            if (string.IsNullOrEmpty(searchCriteria.ListingType) == false)
            {
                //Project Or Property Or Project Directory
                items = items.Where(x=>x.ListingType.Equals(searchCriteria.ListingType));
            }

            if(searchCriteria.Status.HasValue){
                // Status
                items = items.Where(x => x.StatusFID.Equals(searchCriteria.Status));
            }
            if (string.IsNullOrEmpty(searchCriteria.ListingCat) == false)
            {
                // Status
                items = items.Where(x => x.ListingCat.Equals(searchCriteria.ListingCat));
            }
            //Search by City
            if (searchCriteria.CityID.HasValue)
            {
                //Local or International
                items = items.Where(x => x.CityFID == searchCriteria.CityID.Value);
            }
            //Search by Location
            if (searchCriteria.LocationID.HasValue)
            {
                //Local or International
                items = items.Where(x => x.LocaltionFID == searchCriteria.LocationID.Value);
            }
            //Search by Subarea
            if (searchCriteria.SubAreaID.HasValue)
            {
                //Local or International
                items = items.Where(x => x.SubAreaFID == searchCriteria.SubAreaID.Value);
            }
            //Search by PropertyType
            if (searchCriteria.PropertyTypeID.HasValue)
            {
                //Local or International
                items = items.Where(x => x.PropertyTypeFID == searchCriteria.PropertyTypeID.Value);
            }
            //Search by Property Classification
            if (string.IsNullOrEmpty(searchCriteria.PropertyClassification) == false)
            {
                //Local or International
                items = items.Where(x => x.PropertyClsssm.Equals(searchCriteria.PropertyClassification));
            }
            //
            //Search by Tenure
            if (string.IsNullOrEmpty(searchCriteria.Tenure) == false)
            {
                //Local or International
                items = items.Where(x => x.Tenure.Contains(searchCriteria.Tenure.Trim()));
            }
            //Search by Keyword
            if (string.IsNullOrEmpty(searchCriteria.Keyword) == false)
            {
                //Local or International
                items = items.Where(x => x.ProjectName.Contains(searchCriteria.Keyword.Trim()));
            }
            //
            if (string.IsNullOrEmpty(searchCriteria.CityName) == false)
            {
                //Local or International
                items = items.Where(x => x.City.Contains(searchCriteria.CityName.Trim()));
            }
            //
            return items;
        }
        public int CountListings(ListingSearchCriteria searchCriteria)
        {
            var items = SearchByCriteria(searchCriteria);
            return items.Count();
        }

        public int Post(Model.Listings l)
        {
            int? ID = null;
            if(l.ID != 0){
                ID = l.ID;
            }
            int listingid = DataContext.sp_post_listing(ID,l.PropertyFor, l.ProjectNameFID, l.StreetNameFID, l.PropertyClsssm,l.PropertyTypeFID, l.CountryFID, l.CityFID,l.LocaltionFID,l.SubAreaFID,l.Tenure,l.FloorLevel,l.TotalFloor,l.FloorArea_SM,l.FloorArea_SF,l.FloorArea_SY,l.FloorAreaUnit,l.LandArea_SM,l.LandArea_SF,l.LandArea_SY,l.LandAreaUnit,l.AskingPriceLocal,l.AskingPriceUSD,l.PriceInRMBPerSQMLocal,l.PriceInRMBPerSQMUSD,l.ListingType,l.ListingCat,l.NewLaunch,l.Bedroom,l.Bathroom,l.Description,l.DescriptionLocal,l.MemberFID,l.City,l.EfficiencyRate,l.Auction,l.PriceUnit,l.HouseNumber);
            return listingid;           

        }
        public void ChangeStatus(string arrayId, int status)
        {
            DataContext.sp_listing_change_status(arrayId,status);
        }
        //Listing Detail
        public void SaveDetail(Model.ListingDetail item)
        {
            DataContext.sp_listing_detail(item.ListingFID, item.LanguageID, item.Developer, item.Company, item.SiteArea, item.Carpark, item.TotalUnit, item.ExpectedTOP, item.YearCompletion, item.Specifications, item.BuildingDesign, item.Concept, item.Architect, item.Landscape);
        }
        //
        public void UpdateFacilitiesFeatures(int id, string features, string facilities)
        {
            DataContext.sp_listing_facilities_features(id, features, facilities);
        }
        //
        public Model.ListingDetail GetDetail(int id, int lang)
        {
            var item = DataContext.ListingDescItems.SingleOrDefault(x => x.ListingFID.Equals(id) && x.LanguageFID.Equals(lang));
            if (item != null)
            {
                return new Model.ListingDetail
                {
                    ListingFID = item.ListingFID,
                    LanguageID = item.LanguageFID,
                    Developer = item.Developer,
                    Company = item.Company,
                    SiteArea = item.SiteArea,
                    Carpark = item.Carpark,
                    TotalUnit = item.TotalUnit,
                    ExpectedTOP = item.ExpectedTOP,
                    YearCompletion = item.YearCompletion,
                    Specifications = item.Specifications,
                    BuildingDesign = item.BuildingDesign,
                    Concept = item.Concept,
                    Architect = item.Architect,
                    Landscape = item.Landscape
                };
            }
            else
            {
                return null;
            }
        }
        //
    }
}
